package org.autumn.thread;

import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * 二阶段终止
 */
public class TwoPhaseTermination {
    public static void main(String[] args) {
        Monitor monitor = new Monitor();
        monitor.start();
        new Scanner(System.in).next();
        monitor.end();
    }
}


// 监控线程
class Monitor{
    private Thread monitor;

    public void start(){
        monitor = new Thread(()->{
            System.out.println("start monitor ...");
            while (true){
                if (monitor.isInterrupted()){
                    System.out.println("end ...");
                    break;
                }
                try {
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println("monitor ...");
                } catch (InterruptedException e) {
                    System.out.println("sleep interrupt ...");
                    // 重置标记
                    monitor.interrupt();
                }
            }
        });
        monitor.start();
    }

    public void end(){
        monitor.interrupt();
    }
}
